/**
 * 双向链表
 * 能够使用常数时间求得某个节点的直接前驱节点
 * 适用于经常找前驱节点
 */

 class Node {
     constructor (data = null, prior = null, next = null) {
        this.data = data
        this.prior = prior
        this.next = next
     }
 }

class DoubleChain {
    constructor () {
        this.data = new Node()
    }
    create (array) {
        let status = 'range_error'
        if (Array.isArray(array)) {
            let q = this.data,
                i = array.length - 1,
                s
            while (i >= 0) {
                let p = new Node()
                p.data = array[i]
                s = q.next
                q.next = p
                p.prior = q
                if (s) {
                    p.next = s
                    s.prior = p
                }
                i--
            }
            this.data = q
            status = 'success'
        }  
        return status
    }
    locate (pos) {
        let status = 'range_error',
            p = this.data.next,
            i = 1
        while (p && i < pos) {
            i++
            p = p.next
        }
        if (p && i === pos) {
            console.log(p)
            status = 'success'
        }
        return status
    }
    insert (pos, val) {
        let status = 'range_error',
            q = this.data,
            s = new Node(val),
            i = 0,
            p
        while (q && i < pos - 1) {
            q = q.next
            i++
        }
        if (q && i === pos - 1) {
            p = q.next
            q.next = s
            s.prior = q
            if (s) {
                p.next = s
                s.prior = p
            }
            status = 'success'
        }
        return status
    }
    remove (pos) {
        let status = 'range_error',
            q = this.data,
            i = 0,
            p
        while (q && i < pos) {
            q = q.next
            i++
        }
        if (q && i === pos) {
            q.prior.next = q.next
            q.next.prior = q.prior
            status = 'success'
        }
        return status
    }
}

var a = new DoubleChain()
a.create([1, 2, 'hi', 'dtx', 'name'])
console.log(a.data)
a.insert(1, 'hh')
console.log(a.data)